package org.lhq;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.lhq.realm.CustomerRealm;

/**
 * 使用自定义realm
 **/
public class TestCustomerRealmAuthenticator {
    public static void main(String[] args) {
        //1.创建SecurityManager
 DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //2.给安全管理器设置realm（设置为自定义realm获取认证数据）
        defaultSecurityManager.setRealm(new CustomerRealm());
        //IniRealm realm = new IniRealm("classpath:shiro.ini");

        //3.给安全工具类中设置默认安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //4.获取主体对象subject
        Subject subject = SecurityUtils.getSubject();
        //5.创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("xiaochen","123");

        try {
            subject.login(token);//ctr_alt+t调用
            System.out.println(subject.isAuthenticated()+"登录成功");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        }

        //认证用户进行授权
        if(subject.isAuthenticated()){
            //1,基于角色权限控制
            System.out.println(subject.hasRole("admin"));

        }
    }
}
